(function(){
	var position='absolute';
	var elements=[];
	//创建蛇对象
	function Snake(options){
		options=options||{};
		this.width=options.width||20;
		this.height=options.height||20;
		this.direction=options.direction||'right';
		this.body=[
			//蛇头
			{x:3,y:2,color:'red'},
			//蛇身
			{x:2,y:2,color:'blue'},
		    //蛇尾
		    {x:1,y:2,color:'blue'}
		]
	}
	Snake.prototype.render=function(map){
		remove();
		//把每一个蛇节渲染到地图上
		for(var i=0,len=this.body.length;i<len;i++){
			var obj=this.body[i];
		var div=document.createElement('div');
		map.appendChild(div);
		elements.push(div);
		div.style.width=this.width+'px';
		div.style.height=this.height+'px';
		div.style.position=position;
		div.style.left=obj.x*this.width+'px';
		div.style.top=obj.y*this.height+'px';
		div.style.backgroundColor=obj.color;
	}
		
	}
	function remove(){
		for(var i=elements.length-1;i>=0;i--){
			elements[i].parentNode.removeChild(elements[i]);
			elements.splice(i,1);
		}
	}
	
	Snake.prototype.move=function(food,map){
		//移动蛇的身体,让当前蛇节,到上一个蛇节的位置
		for (var i=this.body.length-1;i>0;i--){
			this.body[i].x=this.body[i-1].x;
			this.body[i].y=this.body[i-1].y
		}
		//控制蛇头的移动,判断蛇头的方向
		var head=this.body[0];
		switch(this.direction){
			case 'right':
				head.x+=1;
				break;
			case 'left':
				head.x-=1;
				break;
			case 'top':
				head.y-=1;
				break;
			case 'bottom':
				head.y+=1;
				break;
		}
		//判断蛇头是否和食物重合
		var headX=head.x*this.width;
		var headY=head.y*this.height;
		if(headX===food.x&&headY===food.y){
			var last=this.body[this.body.length-1];
			this.body.push({
				x:last.x,
				y:last.y,
				color:last.color
			})
			food.render(map);
	}
		}
		
	window.Snake=Snake;
	
})()
 